import React from 'react'
import { Navigate, useLocation } from 'react-router-dom'
import { useSelector } from 'react-redux'
import { hasPermission } from '../utils/permission'
import type { RootState } from '../store/types'

interface RoutePermissionGuardProps {
  children: React.ReactNode
  requiredPermission: string
  fallbackPath?: string
}

/**
 * 路由权限检查组件
 * 用于保护需要权限的路由，如果用户没有权限则重定向到指定页面
 */
const RoutePermissionGuard: React.FC<RoutePermissionGuardProps> = ({
  children,
  requiredPermission,
  fallbackPath = '/'
}) => {
  const userEmail = useSelector((state: RootState) => state.info.email)
  const location = useLocation()
  
  // 如果没有登录，重定向到登录页面
  if (!userEmail) {
    return <Navigate to="/login" state={{ from: location }} replace />
  }
  
  // 检查权限
  if (hasPermission(userEmail, requiredPermission)) {
    return <>{children}</>
  }
  
  // 权限不足，重定向到指定页面
  return <Navigate to={fallbackPath} replace />
}

export default RoutePermissionGuard
